#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <arpa/inet.h>

#include "envir.h"
#include "pack.h"
#include "sndfile.h"
#include "main.h"

unsigned int filenum = 0;
unsigned int sendfilenum = 0;
long baonum;
char VERSION[20] = "5.1.180210";
char USER[5] = "hhb";
char COMPUTER[20] = "hhb-VirtualBox";
char NAME[10] = "huhaibin";
char GROUP[15] = "WorkGroup";
char PHONE[15] = "9876543210";
char EMAIL[15] = "666@abc.com";
char IP[20] = "192.168.186.188";
char MAC[20] = "08-00-27-92-4c-38";
char SIGN[20] = "AAABBBCCC";




FEIGE_REQ *head = NULL;
int init_head()//初始化链头，链头保存的属性
{	
	head = (struct feigerecv*)malloc(sizeof(struct feigerecv));
	strcpy(head->version,VERSION);
	strcpy(head->user,USER);
	strcpy(head->host,COMPUTER);
	head->cmd = 666;
	strcpy(head->name,NAME);
	strcpy(head->group,GROUP);
	strcpy(head->mac,MAC);
	strcpy(head->phone,PHONE);
	strcpy(head->email,EMAIL);
	strcpy(head->ip,IP);
	strcpy(head->sign,SIGN);
	head->next = NULL;
}


int list_user()//展示上线用户的ip、昵称
{
	FEIGE_REQ *p = head->next;
	printf("\033[0;33;24mhhb#:\033[0m*****************\n");
	while(p != NULL)
	{
		printf("\033[0;33;24mhhb#:\033[0mip:%s ",p->ip);
		printf("name:%s\n",p->name);
		p = p->next;
	}
	printf("\033[0;33;24mhhb#:\033[0m*****************\n");
	return 0;
}

int free_list()//将链表的用户信息刷掉
{
	FEIGE_REQ *p = NULL,*q = NULL;
	q = head->next;
	p = head->next;
	while(p != NULL)
	{
		q = p;
		p = q->next;
		free(q);
	}
	printf("\033[0;33;24mhhb#:\033[0mfree success\n");
	return 0;
}

int main()
{
	srand(time(NULL));
	baonum =  rand()%2147483647;
	init_head();
	memset(rFiles,0,sizeof(rFiles));
	memset(sFiles,0,sizeof(sFiles));

	//FEIGE_REQ *p = NULL;
	//int i;
	char a[30] = {0};
	char buf[8] = {0},name[20] = {0},newsend[1024] = {0};
	pthread_t login,otherlogin,tcpfile;
	pthread_create(&login,NULL,udp_login,NULL);
	pthread_create(&otherlogin,NULL,udp_otherlogin,NULL);
	pthread_create(&tcpfile,NULL,tcp_server,NULL);//创建TCP服务端用来传文件
	while(1)
	{
		printf("\033[0;33;24mhhb#:\033[0m");
		fgets(a,30,stdin);
		if(strncmp("get",a,3) == 0)
			get_env(a);
		else if(strncmp("set",a,3) == 0)
			set_env(a);
		else if(strncmp("list user",a,9) == 0)
			list_user();
		else if(strncmp("free list",a,9) == 0)
			free_list();
		else if(strncmp("send",a,4) == 0)
		{
			sscanf(a,"%s %s %s",buf,name,newsend);
			send_message(name,newsend);
		}
		else if(strncmp("file",a,4) == 0)
		{
			sscanf(a,"%s %s %s",buf,name,newsend);
			send_file(name,newsend);
		}
		else if(strncmp("quit",a,4) == 0)
			break;
	}
}